package com.common.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ExceptionHandlerAdvice {

	private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandlerAdvice.class);
	
	@ResponseStatus(HttpStatus.CONFLICT)//409
	@ExceptionHandler(DataIntegrityViolationException.class)
	public ErrorInfo handleConflict(DataIntegrityViolationException ex) {
		return new ErrorInfo("The object you want to create is already exists.", ex);
	}

	// Fall back
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // 500
	@ExceptionHandler(Exception.class)
	public ErrorInfo handleOtherException(Exception e) {
		LOGGER.error("Unhandled exception", e);
		return new ErrorInfo("Internal server error", e);
	}

}
